const express = require('express');
const router = express.Router();
const db = require('../utils/lowdb.js').getDB('user.json');
const mockjs = require('mockjs');

db.defaults({ list: [] }).write();

router.post('/login', express.json(), (req, res) => {
  console.log(req.body, 'req.body');
  const mobile = req.body.mobile;
  const vcode = req.body.vcode;
  if (vcode !== '246810') {
    return res.json({
      code: 400,
      msg: '验证码不正确',
    });
  }
  const state = db.getState();
  let user = state.list.find((user) => {
    return user.mobile === mobile;
  });
  console.log(user, 'user');
  if (!user) {
    user = { id: mockjs.Random.guid(), mobile };
    state.list.push(user);
    db.setState(state).write();
  }
  res.json({
    code: 200,
    msg: 'ok',
    user,
  });
});

router.delete('/:id', (req, res) => {
  const id = req.params.id;
  const state = db.getState();
  console.log(state, 'state');
  state.list = state.list.filter((user) => user.id !== id);
  db.setState(state).write();
  res.json({
    code: 200,
    msg: '删除成功',
  });
});

module.exports = router;
